import React, { useMemo, useCallback, useEffect, useState, useRef } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity, Dimensions, ActivityIndicator, RefreshControl, Alert } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import ProgressiveImage from './components/ProgressiveImage';
import FilterBar from './components/FilterBar';
import FilterModal, { Filters } from './components/FilterModal';
import { carAPI } from '../services/api';

const { width } = Dimensions.get('window');
const CARD_WIDTH = (width - 16 * 3) / 2;

type Car = {
    _id: string;
    brand: string;
    model: string;
    year: number;
    price: number;
    mileage: number;
    fuelType: string;
    transmission: string;
    color: string;
    condition: string;
    description?: string;
    images: string[];
    location: string;
    contact: string;
    createdAt: string;
    updatedAt: string;
};

const PAGE_SIZE = 20;

const CarListScreen: React.FC = () => {
    const navigation = useNavigation<any>();
    const [cars, setCars] = useState<Car[]>([]);
    const [currentPage, setCurrentPage] = useState<number>(1);
    const [isLoadingMore, setIsLoadingMore] = useState<boolean>(false);
    const [isRefreshing, setIsRefreshing] = useState<boolean>(false);
    const [hasMoreNext, setHasMoreNext] = useState<boolean>(true);
    const [totalItems, setTotalItems] = useState<number>(0);

    const listRef = useRef<FlatList>(null);

    // filters
    const [filters, setFilters] = useState<Filters>({});
    const [filterVisible, setFilterVisible] = useState(false);
    const filterSummary = useMemo(() => {
        const parts: string[] = [];
        if (filters.brand) parts.push(filters.brand);
        if (filters.price) parts.push(`${Math.round(filters.price.min / 10000)}-${Math.round(filters.price.max / 10000)}万`);
        if (filters.mileage) parts.push(`${Math.round(filters.mileage.min / 1000)}-${Math.round(filters.mileage.max / 1000)}千公里`);
        return parts.length ? parts.join(' · ') : '全部车辆';
    }, [filters]);

    // 转换前端筛选条件为后端API参数
    const convertFiltersToAPI = useCallback((filters: Filters) => {
        const apiFilters: any = {};
        
        if (filters.brand) {
            apiFilters.brand = filters.brand;
        }
        
        if (filters.price) {
            apiFilters.minPrice = filters.price.min;
            apiFilters.maxPrice = filters.price.max;
        }
        
        if (filters.mileage) {
            apiFilters.minMileage = filters.mileage.min;
            apiFilters.maxMileage = filters.mileage.max;
        }
        
        return apiFilters;
    }, []);

    const loadCars = useCallback(async (page: number = 1, mode: 'append' | 'replace' = 'replace') => {
        try {
            if (mode === 'replace') {
                setIsRefreshing(true);
            } else {
                setIsLoadingMore(true);
            }

            const apiFilters = convertFiltersToAPI(filters);
            const response = await carAPI.getCars(page, PAGE_SIZE, apiFilters);
            
            const { cars: newCars, pagination } = response.data;
            
            setCars(prev => {
                if (mode === 'replace') return newCars;
                return [...prev, ...newCars];
            });
            
            setCurrentPage(page);
            setTotalItems(pagination.totalItems);
            setHasMoreNext(pagination.hasNextPage);
            
        } catch (error) {
            console.error('加载车辆列表失败:', error);
            Alert.alert('错误', '加载车辆列表失败，请重试');
        } finally {
            setIsLoadingMore(false);
            setIsRefreshing(false);
        }
    }, [filters, convertFiltersToAPI]);

    useEffect(() => {
        // 初始加载
        loadCars(1, 'replace');
    }, []);

    useEffect(() => {
        // filters 变化时重新加载
        loadCars(1, 'replace');
    }, [filters, loadCars]);

    const renderItem = useCallback(({ item }: { item: Car }) => (
        <TouchableOpacity 
            style={styles.card} 
            activeOpacity={0.85}
            onPress={() => navigation.navigate('CarDetail', { carId: item._id })}
        >
            <View style={styles.imageBox}>
                <ProgressiveImage
                    uri={item.images && item.images.length > 0 ? item.images[0] : `https://picsum.photos/seed/${item._id}/600/400`}
                    thumbnailUri={item.images && item.images.length > 0 ? item.images[0] : `https://picsum.photos/seed/${item._id}/60/40`}
                    style={styles.image}
                />
            </View>
            <View style={styles.infoBox}>
                <Text style={styles.title} numberOfLines={1}>
                    {item.brand} · {item.model}
                </Text>
                <Text style={styles.subTitle}>
                    {item.year} 年 | {item.mileage}km | ¥{item.price.toLocaleString()}
                </Text>
                <Text style={styles.details}>
                    {item.fuelType} | {item.transmission} | {item.color}
                </Text>
            </View>
        </TouchableOpacity>
    ), [navigation]);

    const handleEndReached = useCallback(() => {
        if (isLoadingMore || !hasMoreNext) return;
        loadCars(currentPage + 1, 'append');
    }, [isLoadingMore, hasMoreNext, loadCars, currentPage]);

    const handleRefresh = useCallback(() => {
        setHasMoreNext(true);
        loadCars(1, 'replace');
    }, [loadCars]);

    const renderEmptyComponent = () => (
        <View style={styles.footer}>
            <Text style={styles.footerText}>没有匹配的车辆</Text>
        </View>
    );

    return (
        <View style={styles.container}>
            <FilterBar onOpen={() => setFilterVisible(true)} summary={filterSummary} />
            <FlatList
                ref={listRef}
                data={cars}
                keyExtractor={(item) => item._id}
                renderItem={renderItem}
                numColumns={2}
                removeClippedSubviews
                maxToRenderPerBatch={10}
                windowSize={10}
                initialNumToRender={8}
                contentContainerStyle={styles.list}
                columnWrapperStyle={{ justifyContent: 'space-between' }}
                onEndReached={handleEndReached}
                onEndReachedThreshold={0.15}
                refreshControl={(
                    <RefreshControl refreshing={isRefreshing} onRefresh={handleRefresh} colors={["#007AFF"]} tintColor="#007AFF" />
                )}
                ListFooterComponent={
                    isLoadingMore ? (
                        <View style={styles.footer}> 
                            <ActivityIndicator color="#007AFF" />
                            <Text style={styles.footerText}>加载中...</Text>
                        </View>
                    ) : !hasMoreNext ? (
                        <View style={styles.footer}>
                            <Text style={styles.footerText}>没有更多了</Text>
                            <Text style={styles.footerSubText}>共 {totalItems} 辆车</Text>
                        </View>
                    ) : null
                }
                ListEmptyComponent={!isRefreshing ? renderEmptyComponent : null}
            />
            <FilterModal
                visible={filterVisible}
                onClose={() => setFilterVisible(false)}
                onApply={(f) => { setFilters(f); setFilterVisible(false); }}
            />
        </View>
    );
};

const styles = StyleSheet.create({
    card: {
        backgroundColor: '#FFFFFF',
        borderRadius: 12,
        elevation: 2,
        marginBottom: 12,
        overflow: 'hidden',
        width: CARD_WIDTH,
    },
    container: {
        backgroundColor: '#F7F7F7',
        flex: 1,
    },
    details: {
        color: '#999999',
        fontSize: 11,
    },
    footer: { 
        alignItems: 'center',
        justifyContent: 'center',
        paddingVertical: 16 
    },
    footerSubText: { 
        color: '#999',
        fontSize: 12,
        marginTop: 4 
    },
    footerText: { 
        color: '#666',
        fontSize: 14,
        marginTop: 8 
    },
    image: { 
        height: '100%',
        width: '100%' 
    },
    imageBox: { 
        backgroundColor: '#EEE',
        height: CARD_WIDTH * 0.66, 
        width: '100%' 
    },
    infoBox: { padding: 12 },
    list: { padding: 16 },
    subTitle: {
        color: '#666666',
        fontSize: 13,
        marginBottom: 4,
    },
    title: {
        color: '#333333',
        fontSize: 16,
        fontWeight: '600',
        marginBottom: 6,
    },
});

export default CarListScreen;

